﻿using System.Linq;
using System.Xml;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;

namespace Hvam.SharePoint.Search.Tests
{
    public static class TestTools
    {
        public static void EnsureLocation()
        {
            using (var site = new SPSite(TestConstants.Site))
            {
                var serviceContext = SPServiceContext.GetContext(site);

                var applicationProxy = (SearchServiceApplicationProxy)serviceContext.GetDefaultProxy(typeof(SearchServiceApplicationProxy));

                var applictionInfo = applicationProxy.GetSearchServiceApplicationInfo();
                var application = SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(applictionInfo.SearchServiceApplicationId);
                var locationConfigurations = application.LocationConfigurations;

                var locations = locationConfigurations.Where(l => l.InternalName == TestConstants.SiteSearchLocationName);
                if (!locations.Any())
                {
                    var configurationXml = new XmlDocument();
                    configurationXml.Load(TestConstants.SiteSearchLocationName + ".osdx");

                    var locationConfiguration = new LocationConfiguration(configurationXml);
                    locationConfigurations.Add(locationConfiguration);
                }
            }
        }
    }
}
